package com.jeesite.modules.stock.web;

import com.jeesite.common.io.FileUtils;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Date;

@RestController
@RequestMapping("${adminPath}/image")
public class ImageUploadController {

    @Value("${file.baseDir}")
    private String baseDir;

    private final Logger log = LoggerFactory.getLogger(ImageUploadController.class);

    /**
     * 图片上传
     * @param file 文件
     * @return 返回图片路径
     */
    @RequestMapping("uploadImage")
    public String fileUpload(MultipartFile file) {
        String path = "userfiles/fileupload/" + DateUtils.formatDate(new Date());
        File targetDir = new File(baseDir, path);
        if (!targetDir.exists() && !targetDir.mkdirs()) {
            return "error";
        }
        try {
            String fileName = file.getOriginalFilename();
            String extend = FilenameUtils.getExtension(fileName);
            String randomFileName = StringUtils.getRandomStr(10) + "." + extend;
            File targetFile = new File(targetDir, randomFileName);
            file.transferTo(targetFile);
            return path + "/" + randomFileName;
        } catch (IOException e) {
            log.error("图片");
            return "error";
        }
    }
}
